<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserData"
            @change="getUserData"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserData"></el-button>
          </el-input>
        </el-col>

        <el-col :span="1">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="usersList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editUserMessage(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUserMessage(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="assignRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户窗口 -->
    <el-dialog title="添加用户" :visible.sync="showDialog" width="50%" @close="addUserDialogClosed">
      <span>
        <el-form :model="addUserInfo" :rules="addUserRules" ref="addUserRef" label-width="70px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addUserInfo.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserInfo.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserInfo.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUserMessage">确 定</el-button>
        <el-button @click="showDialog = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户信息窗口 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="showEditUserDialog"
      width="50%"
      @close="editUserDialogClosed"
    >
      <el-form :model="userMessage" :rules="editUserRules" ref="editUserRef" label-width="70px">
        <el-form-item label="用户名称">
          <el-input v-model="userMessage.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userMessage.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userMessage.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
        <el-button @click="showEditUserDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="assignRolesVisible"
      width="50%"
      @close="assignRolesClose"
    >
      <p>当前用户：{{currentMessage.username}}</p>
      <p>当前角色：{{currentMessage.role_name}}</p>
      <p>
        分配新角色：
        <el-select v-model="selectRoleData" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSetRole">确 定</el-button>
        <el-button @click="assignRolesVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as allUsersFunc from '@/network/users'

export default {
  name: 'Users',
  data() {
    const passwordRule = (rule, value, callback) => {
      const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,15}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(
        new Error(
          '请输入至少1个大写字母，1个小写字母和1个数字，其他可以是任意字符的密码'
        )
      )
    }
    const emailRule = (rule, value, callback) => {
      const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确格式的邮箱'))
    }
    const mobileRule = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号码'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      usersList: [],
      total: 0,
      showDialog: false,
      addUserInfo: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          },
          { validator: passwordRule, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailRule, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: mobileRule, trigger: 'blur' }
        ]
      },
      showEditUserDialog: false,
      userMessage: {},
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailRule, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: mobileRule, trigger: 'blur' }
        ]
      },
      assignRolesVisible: false,
      currentMessage: {},
      roleList: [],
      selectRoleData: ''
    }
  },
  created() {
    this.getUserData()
  },
  methods: {
    // 获取用户列表数据
    async getUserData() {
      const res = await allUsersFunc.getUsersData(this.queryInfo)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // 切换每页条数调用此方法
    handleSizeChange(pageSize) {
      this.queryInfo.pagesize = pageSize
      this.getUserData()
    },
    // 切换页码调用此方法
    handleCurrentChange(pageNum) {
      this.queryInfo.pagenum = pageNum
      this.getUserData()
    },
    // 修改状态
    async changeStatus(statusMessage) {
      const res = await allUsersFunc.changeStatus(statusMessage)
      if (res.meta.status !== 200) {
        statusMessage.mg_state = !statusMessage.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 显示添加用户对话框
    addUser() {
      this.showDialog = true
    },
    // 监听添加用户对话框的关闭事件
    addUserDialogClosed() {
      // 清空表单
      this.$refs.addUserRef.resetFields()
    },
    // 点击按钮添加新用户
    addUserMessage() {
      // 对要提交的数据进行预校验，valid为false是提交数据有误，为true是提交数据没有问题
      this.$refs.addUserRef.validate(async valid => {
        if (!valid) {
          return false
        } else {
          const res = await allUsersFunc.addUser(this.addUserInfo)
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          // 关闭添加用户对话框
          this.showDialog = false
          // 重新获取一下数据
          this.getUserData()
        }
      })
    },
    // 通过id获取用户信息
    async editUserMessage(id) {
      const res = await allUsersFunc.getUserDataById(id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.userMessage = res.data
      this.showEditUserDialog = true
    },
    // 监听修改用户对话框的关闭事件
    editUserDialogClosed() {
      this.$refs.editUserRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editUserRef.validate(async valid => {
        console.log('valid:' + valid)
        if (!valid) {
          return false
        } else {
          // 发送编辑请求
          const res = await allUsersFunc.editUserMessageById(this.userMessage)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          } else {
            this.showEditUserDialog = false
            this.getUserData()
            this.$message.success(res.meta.msg)
          }
        }
      })
    },
    // 删除用户信息
    async deleteUserMessage(id) {
      const res = await this.$confirm(
        '此操作将永久删除该条数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (res === 'cancel') {
        // 点击取消按钮
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      // 点击确认按钮
      const deleteRes = await allUsersFunc.deleteSingleUserMessage(id)
      console.log(deleteRes)
      if (deleteRes.meta.status !== 200) {
        return this.$message.error(deleteRes.meta.msg)
      }
      // 更新用户列表数据
      this.getUserData()
      // 显示删除成功提示消息
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
    },
    // 点击分配角色按钮
    async assignRoles(role) {
      this.currentMessage = role
      const { data, meta } = await allUsersFunc.getRoleList()
      if (meta.status !== 200) {
        return this.$message.error(meta.msg)
      }
      this.roleList = data
      this.assignRolesVisible = true
    },
    // 点击分配角色确认按钮
    async confirmSetRole() {
      const { meta } = await allUsersFunc.setRole(
        this.currentMessage.id,
        this.selectRoleData
      )
      if (meta.status !== 200) {
        return this.$message.error(meta.msg)
      }
      this.getUserData()
      this.$message.success(meta.msg)
      this.assignRolesVisible = false
    },
    // 监听分配角色对话框关闭
    assignRolesClose() {
      this.currentMessage = {}
      this.selectRoleData = ''
    }
  }
}
</script>

<style lang="less" scoped>
</style>
